package com.wwh.furns.web;

import com.google.gson.Gson;
import com.wwh.furns.entity.Member;
import com.wwh.furns.service.MemberService;
import com.wwh.furns.service.impl.MemberServiceImpl;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.HashMap;
import java.util.Map;

import static com.google.code.kaptcha.Constants.KAPTCHA_SESSION_KEY;

/**
 * @author Albert
 * @date 2024/5/26-15:16
 * @describe 该Servlet处理与member相关的请求
 */
public class MemberServlet extends BasicServlet {
    private MemberService memberService = new MemberServiceImpl();

    //@Override
    //protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
    //    doPost(req, resp);
    //}

    //@Override
    //protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
    //    //System.out.println("MemberServlet is called...");
    //
    //    String action = req.getParameter("action");
    //    if("login".equals(action)){
    //        login(req, resp);
    //    } else if ("register".equals(action)) {
    //        register(req, resp);
    //    } else {
    //        PrintWriter writer = resp.getWriter();
    //        writer.write("action error");
    //        writer.flush();
    //        writer.close();
    //    }
    //}

    /**
     * 处理用户登陆请求
     *
     * @param req
     * @param resp
     * @throws ServletException
     * @throws IOException
     */
    public void login(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        //接收用户登录信息
        String username = req.getParameter("username");
        String password = req.getParameter("password");
        req.setAttribute("username", username);

        //判断用户名是否可登录
        Member member = new Member(null, username, password, null);
        member = memberService.loginMember(member);
        if (member != null) {
            //登录
            //System.out.println("登录成功");
            HttpSession session = req.getSession();
            session.setAttribute("member", member);
            if (member.getUsername().equals("admin")) {
                req.getRequestDispatcher("/views/manage/manage_menu.jsp").forward(req, resp);
            } else {
                req.getRequestDispatcher("/views/member/login_ok.jsp").forward(req, resp);
            }
        } else {
            //System.out.println("登录失败");
            req.setAttribute("errorMsg", "用户名或密码错误~");
            req.getRequestDispatcher("/views/member/login.jsp").forward(req, resp);

        }
    }

    /**
     * 处理用户注册请求
     *
     * @param req
     * @param resp
     * @throws ServletException
     * @throws IOException
     */
    public void register(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        //接收用户注册信息
        String username = req.getParameter("username");
        String password = req.getParameter("password");
        String email = req.getParameter("email");
        //获取用户提交的验证码
        String code = req.getParameter("code");

        //从session获取验证码
        String token = (String) req.getSession().getAttribute(KAPTCHA_SESSION_KEY);
        //使得该验证码失效
        req.getSession().removeAttribute(KAPTCHA_SESSION_KEY);

        //判断验证码是否有效
        if (token.equalsIgnoreCase(code)) {
            //判断用户名是否可用
            if (!memberService.isExistsUsername(username)) {
                //注册
                //System.out.println("用户名 " + username + " 不存在");
                Member member = new Member(null, username, password, email);
                if (memberService.registerMember(member)) {
                    //System.out.println("注册成功");
                    req.setAttribute("errorMsg", "注册成功~");
                    req.getRequestDispatcher("/views/member/login.jsp").forward(req, resp);
                } else {
                    //System.out.println("注册失败");
                    req.setAttribute("errorMsg", "注册失败，请重新尝试~");
                    req.getRequestDispatcher("/views/member/login.jsp").forward(req, resp);
                }
            } else {
                //返回登录界面
                req.setAttribute("errorMsg", "用户名已存在~");
                req.getRequestDispatcher("/views/member/login.jsp").forward(req, resp);
            }
        } else {
            req.setAttribute("errorMsg", "验证码错误~");
            req.setAttribute("active", "register");
            req.setAttribute("username", username);
            req.setAttribute("email", email);
            req.getRequestDispatcher("/views/member/login.jsp").forward(req, resp);
        }
    }

    /**
     * 用户注销登录状态
     * @param req
     * @param resp
     * @throws ServletException
     * @throws IOException
     */
    public void logout(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        //销毁当前用户的session，并刷新页面到首页
        req.getSession().invalidate();
        resp.sendRedirect(req.getContextPath());
    }

    /**
     * 验证某个用户名是否存在db
     * @param req
     * @param resp
     */
    public void isExistUserName(HttpServletRequest req, HttpServletResponse resp) {
        //获取用户名
        String username = req.getParameter("username");
        //查询是否存在
        boolean existsUsername = memberService.isExistsUsername(username);
        //使用拼接的方法返回
        //String resultJson = "{\"isExist\":+" + existsUsername + "}";

        //使用Map转成Json返回
        Map<String, Object> resultMap = new HashMap<>();
        resultMap.put("isExist", existsUsername);
        Gson gson = new Gson();
        String resultJson = gson.toJson(resultMap);

        // 返回
        try {
            resp.getWriter().write(resultJson);
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
    }

    /**
     * 检查验证码是否正确
     * @param req
     * @param resp
     */
    public void isCodeRight(HttpServletRequest req, HttpServletResponse resp) {
        //获取用户提交的验证码
        String code = req.getParameter("code");

        //从session获取验证码
        String token = (String) req.getSession().getAttribute(KAPTCHA_SESSION_KEY);

        boolean isCodeRight = false;
        if(token != null){
            isCodeRight = token.equals(code);
        }


        //使用Map转成Json返回
        Map<String, Object> resultMap = new HashMap<>();
        resultMap.put("isCodeRight", isCodeRight);
        Gson gson = new Gson();
        String resultJson = gson.toJson(resultMap);

        // 返回
        try {
            resp.getWriter().write(resultJson);
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
    }
}
